package com.mj.mes.system.SysUser;/**
 * @author cRyann
 * @create 2017-03-27 15:37
 **/

import com.mj.mes.system.SysResource.SysResource;
import com.mj.mes.system.SysRole.SysRole;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @author cRyann
 * @create 2017-03-27 15:37
 **/
@Service
@Transactional
@ConfigurationProperties(value = "sysUserService")
public class SysUserService {
    @Autowired
    private SysUserDao sysUserDao;

    public SysUser findOne(String username){
        return sysUserDao.findByUserName(username);
    }

    public Set<SysRole> getRolesBySysUserName(String username){
        return sysUserDao.findByUserName(username).getRoles();
    }

    public Set<SysResource> getResourceBySysUserName(String username){
        Set<SysRole> roles = sysUserDao.findByUserName(username).getRoles();
        Set<SysResource> sysResources = new HashSet<SysResource>();
        for (SysRole role : roles){
            Set<SysResource> resources = role.getSysresources();
            for (SysResource resource : resources)
                sysResources.add(resource);
        }
        return sysResources;
    }

    public Page<SysUser> findAll(Pageable pageable) {
        return sysUserDao.findAll(pageable);
    }
    public List<SysUser> findAll(){
        return sysUserDao.findAll();
    }

    /**
     * 删除
     * @param list
     * @return
     */
    public boolean delete(List<SysUser> list){
        boolean flag=false;
        try {
            sysUserDao.deleteInBatch(list);
            flag=true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return flag;
    }

    /**
     * 根据id查找
     * @param id
     * @return
     */
   public SysUser findOne(Long id){
        return sysUserDao.findOne(id);
    }

    /**
     * 更新用户
     * @param sysUser
     */
    public void updateUser(SysUser sysUser){
        sysUserDao.save(sysUser);
    }

    public void addUser(SysUser sysUser){
        sysUserDao.save(sysUser);
    }
}
